import { login, getInfo, logout } from '@/api/user';
import { getToken, setCookie, getCookie, removeCookie, setToken, removeToken } from '@/utils/auth';
// import { resetRouter } from '@/router'
// import { _axios } from '@/api/apiConfig'

interface IUserState {
    token: string;
    name: string;
    avatar: string;
    userId: string;
    userNo: string;
    refreshToken: string;
    moduleIds: string[];
    socketInfo: any[];
}
const state: IUserState = {
    token: getToken(),
    refreshToken: '',
    name: '',
    moduleIds: [],
    socketInfo: [],
    userNo: '',
    userId: '',
    avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
};

const mutations = {
    SET_TOKEN: (state: IUserState, token: string) => {
        state.token = token;
    },
    SET_NAME: (state: IUserState, name: string) => {
        state.name = name;
    },
    SET_USERID: (state: IUserState, userId: string) => {
        state.userId = userId;
    },

    SET_AVATAR: (state: IUserState, avatar: string) => {
        state.avatar = avatar;
    },
    SET_MODULEIDS(state: IUserState, moduleIds: string[]) {
        state.moduleIds = moduleIds;
    },
    SET_REFRESHTOKEN(state: IUserState, refreshToken: string) {
        state.refreshToken = refreshToken;
    },
    SET_USERNO(state: IUserState, userNo: string) {
        state.userNo = userNo;
    },
    SET_TEMP_COOKIE({ token, refreshToken }) {
        setCookie('tempToken', token);
        setCookie('tempRefreshToken', refreshToken);
    },
    PUSH_SOCKET_INFO(state: IUserState, socketInfo: any) {
        const index = state.socketInfo.findIndex((item) => item.id === socketInfo.id);
        if (index > -1) {
            state.socketInfo.splice(index, 1, socketInfo);
        } else {
            state.socketInfo.push(socketInfo);
        }
    },
    DELETE_SOCKET_INFO(state: IUserState, socketInfo: any) {
        const index = state.socketInfo.findIndex((item) => item.id === socketInfo.id);
        index > -1 && state.socketInfo.splice(index, 1);
    },
    DELETE_SOCKET_INFO_ALL(state: IUserState, socketInfo: any) {
        state.socketInfo = socketInfo;
    }
};

const actions = {
    login({ commit }: any, userInfo: any) {
        const { userNo, password } = userInfo;
        return new Promise((resolve, reject) => {
            login({ userNo, password })
                .then((response: any) => {
                    const {
                        data: { token, userName, userNo, userId, refreshToken }
                    } = response;

                    commit('SET_USERID', userId);
                    commit('SET_NAME', userName);
                    commit('SET_USERNO', userNo);
                    commit('SET_TOKEN', token);
                    commit('SET_REFRESHTOKEN', refreshToken);
                    // 这里存储多个 token 是为了支持 多用户去登陆
                    // commit('SET_TEMP_COOKIE', { token, refreshToken })
                    // setCookie(`${userId}_refreshToken`, refreshToken)
                    // setCookie(`${userId}_token`, token)
                    setToken(token);
                    setCookie('refreshToken', refreshToken);

                    resolve();
                })
                .catch((error: any) => {
                    reject(error);
                });
        });
    },

    getInfo({ commit }) {
        // const refreshToken = state.refreshToken || getCookie('tempRefreshToken')
        const refreshToken = state.refreshToken || getCookie('refreshToken');
        return new Promise((resolve, reject) => {
            getInfo(refreshToken)
                .then((response) => {
                    const {
                        data: { token, userName, userNo, userId, refreshToken }
                    } = response;
                    console.log('getInfo response', response);
                    commit('SET_TOKEN', token);
                    commit('SET_REFRESHTOKEN', refreshToken);
                    commit('SET_USERID', userId);
                    commit('SET_NAME', userName);
                    commit('SET_USERNO', userNo);
                    resolve();
                })
                .catch((error) => {
                    reject(error);
                });
        });
    },
    // user logout
    logout({ commit }) {
        // const refreshToken = getCookie('refreshToken')
        const refreshToken = state.refreshToken || getCookie('tempRefreshToken');
        return new Promise((resolve, reject) => {
            logout(refreshToken)
                .then(() => {
                    // 这里存储多个 token 是为了支持 多用户去登陆
                    // removeCookie(`${state.userId}_token`)
                    // removeCookie(`${state.userId}_refreshToken`)
                    // removeCookie('tempToken')
                    // removeCookie('tempRefreshToken')
                    removeToken();
                    removeCookie('refreshToken');
                    commit('SET_TOKEN', '');
                    commit('SET_USERID', '');
                    commit('SET_NAME', '');
                    commit('SET_REFRESHTOKEN', '');
                    commit('SET_USERNO', '');
                    location.reload();
                    resolve();
                })
                .catch((error: any) => {
                    reject(error);
                });
        });
    },

    // remove token
    resetToken({ commit }) {
        return new Promise((resolve) => {
            // 这里存储多个 token 是为了支持 多用户去登陆
            // removeCookie(`${state.userId}_token`)
            // removeCookie(`${state.userId}_refreshToken`)
            // removeCookie('tempToken')
            // removeCookie('tempRefreshToken')
            removeToken();
            removeCookie('refreshToken');

            commit('SET_TOKEN', '');
            commit('SET_USERID', '');
            commit('SET_NAME', '');
            commit('SET_REFRESHTOKEN', '');
            commit('SET_USERNO', '');
            commit('SET_TOKEN', '');
            resolve();
        });
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions
};
